package org.hongqi.common.senpec.base.spring.security;

import jakarta.servlet.http.Cookie;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hongqi.common.senpec.base.sevlet.ResponseService;
import org.hongqi.common.senpec.base.spring.redis.RedisService;
import org.hongqi.common.senpec.base.spring.security.jwt.JWTService;
import org.hongqi.common.senpec.base.utils.ObjectsUtil;
import org.hongqi.common.senpec.sys.user.User;
import org.hongqi.common.senpec.sys.user.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
@RequiredArgsConstructor
public class SpringSecurityHandlers {

    private final ResponseService responseService;

    private final UserService userService;

    private final JWTService jwtService;

    private final RedisService<String> redisService;

    @Value("${spring.application.name}")
    private String applicationName;

    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler() {
        return (request, response, authentication) -> {
            log.info("authenticationSuccessHandler with {} is running.........", authentication.getName());
            User user = userService.myGetByUsername(authentication.getName());
            String token = jwtService.generateToken(user);
            redisService.setOne(applicationName + "-" + user.getUsername() + "-token", token);
            Cookie cookie1 = new Cookie("token", token);
            cookie1.setMaxAge(60 * 30);
            Map<Object, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("status", true);
            map.put("msg", "登录成功。");
            map.put("type", "success");
            map.put("user_username", user.getUsername());
            map.put("user_name", user.getName());
            map.put("user_id", user.getId());
            responseService.generateResponse(response, map);
        };
    }

    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return (request, response, exception) -> {
            log.info("authenticationFailureHandler is running.........");
            String username = request.getParameter("username");
            User user1 = userService.myGetByUsername(username);
            Map<Object, Object> map = new HashMap<>();
            map.put("msg", ObjectsUtil.isNullOrEmpty(user1) ? "帐号错误" : "密码错误");
            map.put("type", "error");
            map.put("status", false);
            responseService.generateResponse(response, map);
        };
    }

    @Bean
    public LogoutHandler logoutHandler() {
        return (request, response, authentication) -> {
            log.info("LogoutHandler is running............");
            String username = jwtService.extractUsername(request.getHeader("Authorization"));
            redisService.deleteKey(applicationName + "-" + username + "-token");
        };
    }

    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() {
        return (request, response, authentication) -> {
            log.info("LogoutSuccessHandler is running...........");
            Map<Object, Object> map = new HashMap<>();
            map.put("status", true);
            map.put("msg", "注销成功");
            map.put("type", "success");
            responseService.generateResponse(response, map);
        };
    }


}
